<template>
	<el-dialog class="dialog" v-model="userStore.chatComponentIsView" width="800" top="3vh" @open="open" @close="clear">
		<el-row style="display: flex; justify-content: space-between;">
			<el-col :span="6">
				<h1>{{ userStore.chatName }}</h1>
			</el-col>
			<el-col :span="1">
				<MoreFilled style="margin-top: 20px; cursor: pointer;" @click="isShowDrawer = true;" />
			</el-col>
			<el-drawer v-model="isShowDrawer" class="Drawer" size="20%">
				<div class="flex">
					<div class="ChatRoomInfo">
						<p>聊天室名称</p>
						<p>{{ userStore.chatName }}</p>
						<p>聊天记录</p>
					</div>
					<el-row>
						<el-col :span="8"><el-button type="primary" @click="memberSearch">群成员</el-button></el-col>
						<el-col :span="8"><el-button type="primary" @click="typeSearch">消息类型</el-button></el-col>
						<el-col :span="8"><el-button type="primary" @click="dateSearch">消息日期</el-button></el-col>
					</el-row>
					<el-scrollbar ref="drawerScrollbar" class="DrawerScrollbar">
						<info-component v-for="(item,index) in list" :key="index" :info="item.value1"
							:searchInfo="item.value2" :searchType="searchType"></info-component>
					</el-scrollbar>
				</div>
			</el-drawer>
		</el-row>
		<hr />
		<el-scrollbar ref="scrollbar" class="view">
			<div ref="scrollbarHeight">
				<p class="AddMessageList" v-if="pageNow < userStore.pages " @click="getOldMessage">查找更早的聊天记录</p>
				<MessageComponent v-for="(item, index) in userStore.messageList" :key="index"
					:message="JSON.parse(item).content"
					:isMe='JSON.parse(item).senderId == userStore.userId ? true : false'
					:avatar="findUser(JSON.parse(item).senderId).avatar"
					:name="findUser(JSON.parse(item).senderId).userName" :type="JSON.parse(item).type">
				</MessageComponent>
			</div>
		</el-scrollbar>
		<div style="display: flex; align-items: center;">
			<el-upload class="upload" :on-error="showError"
				:action="api.url+'/uploadImage/' + userStore.userId+'/'+userStore.chatId" :headers="api.header"
				:show-file-list="false">
				<el-icon :size="50">
					<UploadFilled />
				</el-icon>
			</el-upload>
			<span v-if="isShowError == true" style="color: red;">发送内容不能为空！</span>
		</div>
		<el-input class="input" type="textarea" v-model="input" resize="none" :rows="4"
			@keydown.ctrl.enter="sendPrivateMessage" />
		<p style="text-align: right">
			<el-button type="success" @click="sendPrivateMessage">发送</el-button>
		</p>
	</el-dialog>
</template>
<script setup>
	import {
		useUser
	} from '@/store';
	import {
		ref,
		nextTick,
		watch
	} from 'vue';
	import MessageComponent from './MessageComponent.vue';
	import {
		ElMessage,
		ElScrollbar
	} from 'element-plus';
	import api from '@/api/service'
	import InfoComponent from './InfoComponent.vue';
	const userStore = useUser();
	const input = ref(""); //用户输入
	const scrollbar = ref(null); //滚动条实例
	const scrollbarHeight = ref(null);
	const pageNow = ref(0); //现在的页数
	const isShowError = ref(false); //是否显示错误提醒
	const isShowDrawer = ref(false); //是否显示抽屉
	const searchType = ref(null);
	const list = ref([]);
	//发消息
	const sendPrivateMessage = () => {
		if (input.value.trim() == 0) {
			isShowError.value = true;
			return;
		}
		var data = {
			senderId: userStore.userId,
			receiverId: userStore.chatId,
			content: input.value,
			createTime: Date.parse(new Date()),
			type: 0,
		};
		clear();
		userStore.websocket.send(JSON.stringify(data));
	};
	//滚动到底
	const scrollBottom = async () => {
		await nextTick(); //等待dom更新
		//setScrollTop 是滚动区域实例（ref）的api ， offsetHeight 是滚动区域里面的最大div实例的属性(div的高度)
		scrollbar.value.setScrollTop(scrollbarHeight.value.offsetHeight); //这里有个Bug当显示的是图片的话，高度差一些

	}
	//根据信息的发送者Id从用户列表得到信息
	const findUser = userId => {
		for (var item of userStore.userList)
			if (item.userId == userId) return {
				avatar: item.avatar,
				userName: item.userName
			}
	}
	//弹窗打开调用的初始化函数
	const open = () => {
		scrollBottom();
	}
	const clear = () => {
		input.value = ""; //先清空输入框
		pageNow.value = 0;
		isShowError.value = false;
		list.value = [];
	}
	const showError = () => {
		ElMessage.error("上传文件过大");
	}
	const getOldMessage = () => {
		pageNow.value += 1;
		api.getOldMessage(userStore.chatId, pageNow.value).then(resp => {
			for (var item of resp) userStore.messageList.unshift(JSON.stringify(item));
		})
	}
	//挂载监听器，监听是否要滚动到底
	watch(() => userStore.isScrollBottom, scrollBottom);
	const memberSearch = () => {
		list.value = [];
		searchType.value = 1;
		for (var item of userStore.userList) list.value.push({
			value1: item.userName,
			value2: item.userId
		});
	}
	const typeSearch = () => {
		list.value = [];
		searchType.value = 2;
		var messageList = [{
			value1: '文字',
			value2: 0
		}, {
			value1: '图片',
			value2: 1
		}];
		list.value = messageList;
	}
	const dateSearch = () => {
		list.value = [];
		searchType.value = 3;
		console.log(searchType.value)
		api.getTimeListInChatRoom(userStore.chatId).then(resp => {
			list.value = resp;
		});
	}
</script>
<style scoped>
	.view {
		height: 50vh;
	}

	.upload {
		margin-top: 20px;
	}

	.input {

		border: 1px solid #ccc;
		/* 添加边框 */
		border-radius: 4px;
		/* 添加边框圆角 */
		/* width: calc(100% - 20px); 计算输入框宽度，考虑边框 */
		font-size: 20px;
	}

	.AddMessageList {
		font-size: 12px;
		color: aqua;
		text-align: center;
		margin-top: -2px;
	}

	.flex {
		display: flex;
		flex-direction: column;
	}

	.ChatRoomInfo {
		font-size: 24px;
	}

	.DrawerScrollbar {
		width: 100%;
		flex: 1;

	}
</style>